package com.chat.consumer.rpc;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.CharsetUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @Auther created by haoteng on 2019/08/16
 */
public class DemoClientInChannelHandler extends ChannelInboundHandlerAdapter {

    Logger log = LoggerFactory.getLogger(DemoClientInChannelHandler.class);

    /**
     * 在到服务器的连接已经建立之后将被调用
     *
     * @param ctx
     * @throws Exception
     */
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        log.info("客户端与服务器建立连接信息 : " + ctx.channel().remoteAddress() + "!");
        ctx.fireChannelActive();
    }

    /**
     * 在处理过程中引发异常时被调用
     *
     * @param ctx
     * @param cause
     * @throws Exception
     */
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        ctx.close();
    }

    /**
     * 当从服务器接收到一个消息时被调用
     *
     * @param channelHandlerContext
     * @throws Exception
     */
    @Override
    public void channelRead(ChannelHandlerContext channelHandlerContext, Object s) throws Exception {
        ByteBuf in = (ByteBuf) s;
        System.out.println("客户端收到信息: " + in.toString(CharsetUtil.UTF_8));
    }

    @Override
    public void channelRegistered(ChannelHandlerContext ctx) throws Exception {
        log.info("注册信息");
        ctx.fireChannelRegistered();
    }

    @Override
    public void channelUnregistered(ChannelHandlerContext ctx) throws Exception {
        log.info("取消注册信息");
        ctx.fireChannelUnregistered();
    }
}
